// src/components/RealTimeChart.jsx
import React, { useState, useEffect, useRef } from 'react';
import ScatterLineChart from './ScatterLineChart';
import { parseRealTimeData } from '../utils/dataParser';

const RealTimeChart = ({ wsUrl, initialMessage }) => {
  const [data, setData] = useState(null);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState(null);
  const wsRef = useRef(null);
  const timeCounter = useRef(0);

  // 初始化WebSocket连接
  useEffect(() => {
    const connectWebSocket = () => {
      try {
        const ws = new WebSocket(wsUrl);
        
        ws.onopen = () => {
          setIsConnected(true);
          setError(null);
          // 发送初始化消息
          ws.send(JSON.stringify(initialMessage));
        };
        
        ws.onmessage = (event) => {
          const rawData = event.data;
          try {
            // 解析实时数据
            const parsedData = parseRealTimeData(rawData, timeCounter.current);
            timeCounter.current += 1;
            
            setData(prevData => {
              // 如果是第一条数据，初始化数据结构
              if (!prevData) {
                return {
                  title: "实时数据监控",
                  multiSeries: true,
                  allSeries: [
                    {
                      seriesInfo: { name: "A1" },
                      line: [{ value: [parsedData.time, parsedData.A1] }]
                    },
                    {
                      seriesInfo: { name: "A2" },
                      line: [{ value: [parsedData.time, parsedData.A2] }]
                    },
                    {
                      seriesInfo: { name: "A3" },
                      line: [{ value: [parsedData.time, parsedData.A3] }]
                    }
                  ]
                };
              }
              
              // 更新现有数据，保留最近50个数据点
              return {
                ...prevData,
                allSeries: prevData.allSeries.map(series => {
                  const seriesName = series.seriesInfo.name;
                  const newValue = parsedData[seriesName];
                  const newPoint = { value: [parsedData.time, newValue] };
                  
                  return {
                    ...series,
                    line: [...(series.line.length >= 50 ? series.line.slice(1) : series.line), newPoint]
                  };
                })
              };
            });
          } catch (parseError) {
            console.error('数据解析错误:', parseError);
          }
        };
        
        ws.onerror = (error) => {
          setError(`WebSocket错误: ${error.message}`);
          setIsConnected(false);
        };
        
        ws.onclose = () => {
          setIsConnected(false);
          // 尝试重新连接
          setTimeout(connectWebSocket, 5000);
        };
        
        wsRef.current = ws;
      } catch (error) {
        setError(`连接失败: ${error.message}`);
        setIsConnected(false);
      }
    };
    
    connectWebSocket();
    
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, [wsUrl, initialMessage]);

  return (
    <div>
      <div style={{ 
        marginBottom: '10px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <div>
          <span style={{
            display: 'inline-block',
            width: '12px',
            height: '12px',
            borderRadius: '50%',
            backgroundColor: isConnected ? 'green' : 'red',
            marginRight: '8px'
          }}></span>
          {isConnected ? '已连接' : '连接中...'}
        </div>
        {error && <div style={{ color: 'red' }}>{error}</div>}
      </div>
      
      {data ? (
        <ScatterLineChart 
          initialData={data} 
          chartStyle={{
            chartType: 'line',
            showTopAxis: false,
            showBottomAxis: true,
            showLeftAxis: true,
            showRightAxis: false,
            xScaleType: 'value',
            yScaleType: 'value',
            titleShow: true,
            titleText: "实时数据监控",
            xScaleAdjustment: 'auto',
            yScaleAdjustment: 'auto'
          }}
        />
      ) : (
        <div>等待数据...</div>
      )}
    </div>
  );
};

export default RealTimeChart;